//
//  B_HomeSelectView.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/8/11.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_HomeSelectView.h"

@interface B_HomeSelectView()

@property (nonatomic, assign) CGRect myFrame;

@property (nonatomic, strong) NSMutableArray * buttonArray;

@end


@implementation B_HomeSelectView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _myFrame = frame;
        _buttonArray = [NSMutableArray array];
        self.backgroundColor = [UIColor color_content_background_color];
    }
    return self;
}

- (void)setTitleArray:(NSArray *)titleArray {
    _titleArray = titleArray;
    CGFloat width = _myFrame.size.width / (titleArray.count * 1.0);
    for (int i = 0; i < _titleArray.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:_titleArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor color_text_deep_gray] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor color_text_white] forState:UIControlStateSelected];
        button.frame = CGRectMake(width * i, 0, width, _myFrame.size.height);
        if (i == 1) {
            button.titleLabel.font = [UIFont systemFontOfSize:12];
            button.selected = YES;
        } else {
            button.titleLabel.font = [UIFont systemFontOfSize:12];
            button.selected = NO;
        }
        if ([titleArray[i] isEqualToString:@"距离"]) {
            [button setImage:[UIImage imageNamed:@"B_activity_home_juli"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"B_activity_home_juli_sel"] forState:UIControlStateSelected];
            [button layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:10];
        }
        button.tag = i;
        [self.buttonArray addObject:button];
        [self addSubview:button];
        [button addTarget:self action:NSSelectorFromString(@"buttonAction:") forControlEvents:UIControlEventTouchUpInside];
    }
}


- (void) buttonAction:(UIButton *) btn {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        return ;
    });
    for (UIButton * button in self.buttonArray) {
        if (button.isSelected) {
            button.selected = NO;
            button.titleLabel.font = [UIFont systemFontOfSize:12];
            break;
        }
    }
    btn.selected = YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:12];
    if (self.tapActionWithIndex) {
        self.tapActionWithIndex(btn.tag);
    }
    
    
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    for (UIButton * button in self.buttonArray) {
        if (button.isSelected) {
            button.selected = NO;
        }
        if (button.tag == _selectedIndex) {
            button.selected = YES;
        }
    }
}


@end
